import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { ElMessage } from 'element-plus'
import {
    fetchBuyerOrders as apiFetchBuyerOrders,
    fetchSellerOrders as apiFetchSellerOrders,
    createOrder as apiCreateOrder,
    confirmReceipt as apiConfirmReceipt,
    cancelOrder as apiCancelOrder,
    getOrderDetail,
    createOrderReview as apiCreateOrderReview
} from '@/api/order'

export const useOrderStore = defineStore('order', () => {
    // 状态
    const orders = ref<any[]>([])
    const loading = ref(false)
    const currentOrder = ref<any>(null)
    const total = ref(0)

    // 计算属性
    const buyerOrders = computed(() => {
        return orders.value.filter(order => order.buyerId === useUserStore().userInfo.id)
    })

    const sellerOrders = computed(() => {
        return orders.value.filter(order => order.sellerId === useUserStore().userInfo.id)
    })

    const pendingTransactionOrders = computed(() => {
        return orders.value.filter(order => order.status === 1)
    })

    const pendingReviewOrders = computed(() => {
        return orders.value.filter(order => order.status === 4)
    })

    const completedOrders = computed(() => {
        return orders.value.filter(order => order.status === 2)
    })

    const cancelledOrders = computed(() => {
        return orders.value.filter(order => order.status === 3)
    })

    // 检查登录状态
    const checkLogin = () => {
        if (!useUserStore().token) {
            ElMessage.warning('请先登录')
            return false
        }
        return true
    }


    // 获取买家订单列表
    const fetchBuyerOrders = async (params: { page?: number, size?: number, status?: number } = {}) => {
        if (!checkLogin()) return false

        try {
            loading.value = true
            const response = await apiFetchBuyerOrders(params)

            if (response.code === 200) {
                if (params.page === 1 || params.page === undefined) {
                    orders.value = response.data.records || []
                } else {
                    orders.value = [...orders.value, ...(response.data.records || [])]
                }
                total.value = response.data.total || 0
                return true
            }
            return false
        } catch (error) {
            console.error('获取买家订单列表失败:', error)
            return false
        } finally {
            loading.value = false
        }
    }

    // 获取卖家订单列表
    const fetchSellerOrders = async (params: { page?: number, size?: number, status?: number } = {}) => {
        if (!checkLogin()) return false

        try {
            loading.value = true
            const response = await apiFetchSellerOrders(params)

            if (response.code === 200) {
                if (params.page === 1 || params.page === undefined) {
                    orders.value = response.data.records || []
                } else {
                    orders.value = [...orders.value, ...(response.data.records || [])]
                }
                total.value = response.data.total || 0
                return true
            }
            return false
        } catch (error) {
            console.error('获取卖家订单列表失败:', error)
            return false
        } finally {
            loading.value = false
        }
    }

    // 创建订单
    const createOrder = async (orderData: any) => {
        if (!checkLogin()) return false

        try {
            loading.value = true
            const response = await apiCreateOrder(orderData)

            if (response.code === 200) {
                currentOrder.value = response.data
                return response.data
            }
            return null
        } catch (error) {
            console.error('创建订单失败:', error)
            return null
        } finally {
            loading.value = false
        }
    }

    // 获取订单详情
    const getOrder = async (orderId: number) => {
        if (!checkLogin()) return null

        try {
            loading.value = true
            const response = await getOrderDetail(orderId)

            if (response.code === 200) {
                currentOrder.value = response.data
                return response.data
            }
            return null
        } catch (error) {
            console.error('获取订单详情失败:', error)
            return null
        } finally {
            loading.value = false
        }
    }

    // 确认收货
    const confirmReceipt = async (orderId: number) => {
        if (!checkLogin()) return false

        try {
            loading.value = true
            const response = await apiConfirmReceipt(orderId)

            if (response.code === 200) {
                // 更新本地订单状态
                const order = orders.value.find(o => o.id === orderId)
                if (order) {
                    order.status = 4
                    order.completionTime = new Date().toISOString()
                    order.updatedAt = new Date().toISOString()
                }
                return true
            }
            return false
        } catch (error) {
            console.error('确认收货失败:', error)
            return false
        } finally {
            loading.value = false
        }
    }

    // 取消订单
    const cancelOrder = async (orderId: number, reason: string) => {
        if (!checkLogin()) return false

        try {
            loading.value = true
            const response = await apiCancelOrder(orderId, { reason })

            if (response.code === 200) {
                // 更新本地订单状态
                const order = orders.value.find(o => o.id === orderId)
                if (order) {
                    order.status = 3
                    order.cancelTime = new Date().toISOString()
                    order.updatedAt = new Date().toISOString()
                }
                return true
            }
            return false
        } catch (error) {
            console.error('取消订单失败:', error)
            return false
        } finally {
            loading.value = false
        }
    }

    // 创建订单评价
    const createOrderReview = async (orderId: number, reviewData: any) => {
        if (!checkLogin()) return false

        try {
            loading.value = true
            const response = await apiCreateOrderReview(orderId, reviewData)

            if (response.code === 200) {
                // 更新本地订单评价状态
                const order = orders.value.find(o => o.id === orderId)
                if (order) {
                    order.isReviewed = true
                    order.status = 2  // 更新状态为已完成
                    order.updatedAt = new Date().toISOString()
                }
                return true
            }
            return false
        } catch (error) {
            console.error('创建订单评价失败:', error)
            return false
        } finally {
            loading.value = false
        }
    }

    return {
        // 状态
        orders,
        loading,
        currentOrder,
        total,

        // 计算属性
        buyerOrders,
        sellerOrders,
        pendingTransactionOrders,
        pendingReviewOrders,
        completedOrders,
        cancelledOrders,

        // 方法
        fetchBuyerOrders,
        fetchSellerOrders,
        createOrder,
        getOrder,
        confirmReceipt,
        cancelOrder,
        createOrderReview
    }
}) 